package com.wms.catlog.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import com.dianping.cat.Cat;
import com.dianping.cat.message.Message;
import com.dianping.cat.message.Transaction;
import com.wms.catlog.annotation.EventType;

//@WebFilter(filterName="CatServletFilter",urlPatterns="/*")
public class CatServletFilter implements Filter {
	private String[] urlPatterns = new String[0];

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String patterns = filterConfig.getInitParameter("CatHttpModuleUrlPatterns");
		if (patterns != null) {
			patterns = patterns.trim();
			this.urlPatterns = patterns.split(",");

			for (int i = 0; i < this.urlPatterns.length; ++i) {
				this.urlPatterns[i] = this.urlPatterns[i].trim();
			}
		}
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		String uri = request.getRequestURI().toString();
		String[] urlPatterns = this.urlPatterns;
		int length = urlPatterns.length;

		for (int i = 0; i < length; ++i) {
			String urlPattern = urlPatterns[i];
			if (uri.startsWith(urlPattern)) {
				uri = urlPattern;
			}
		}

		Transaction t = Cat.newTransaction(EventType.SERVICE.getValue(), uri);
		PropertyContext propertyContext = new PropertyContext();
		propertyContext.addProperty("_catRootMessageId", request.getHeader("X-CAT-ROOT-ID"));
		propertyContext.addProperty("_catParentMessageId", request.getHeader("X-CAT-PARENT-ID"));
		propertyContext.addProperty("_catChildMessageId", request.getHeader("X-CAT-CHILD-ID"));
		Cat.logRemoteCallServer(propertyContext);
		Cat.logEvent(EventType.SERVICE_METHOD.getValue(), request.getMethod(), Message.SUCCESS,
				request.getRequestURL().toString());
		Cat.logEvent(EventType.SERVICE_CLIENT.getValue(), request.getRemoteHost());
		String clientApp = request.getHeader("X-PPD-CAT-APP");
		Cat.logEvent(EventType.SERVICE_APP.getValue(), clientApp == null ? "unknown" : clientApp);

		try {
			filterChain.doFilter(servletRequest, servletResponse);
			t.setStatus(Message.SUCCESS);
		} catch (Exception ex) {
			t.setStatus(ex);
			Cat.logError(ex);
			throw ex;
		} finally {
			t.complete();
		}
	}

	@Override
	public void destroy() {

	}

}